package com.sxj.shop.service.proxy;

import com.sxj.shop.entity.User;
import com.sxj.shop.exception.*;
import com.sxj.shop.factory.ObjectFactory;
import com.sxj.shop.service.UserService;
import com.sxj.shop.tran.TransactionManager;

/**
 * 交叉业务逻辑:与业务无关的一些额外功能,例如:事务
 * 在交叉业务逻辑中不能改变核心业务逻辑中做的处理
 * 例如:捕获到异常之后,原样抛出去,不做处理
 */
public class UserServiceProxy implements UserService {

    private UserService userService = (UserService) ObjectFactory.getObject("userServiceTarget");
    private TransactionManager tran = (TransactionManager) ObjectFactory.getObject("tran");

    @Override
    public void register(String username, String password, String phone, String address) throws RequestParameterErrorException, UserExistException {
        try {
            // 执行核心业务逻辑之前,开启事务
            tran.begin();
            // 执行核心业务逻辑
            userService.register(username, password, phone, address);
            // 执行核心业务逻辑之后,提交或者回滚事务
            tran.commit();
        } catch (RequestParameterErrorException e) {
            tran.rollback();
            // 此处异常不需要处理,这些异常都是在核心业务逻辑中已经处理过的
            // 因此,直接抛出去,交给表示层进行处理
            throw e;
        } catch (UserExistException e) {
            tran.rollback();
            throw e;
        }
    }

    @Override
    public User login(String username, String password) throws RequestParameterErrorException, UserNotExistException {
        try {
            tran.begin();
            User user = userService.login(username, password);
            tran.commit();
            return user;
        } catch (RequestParameterErrorException e) {
            tran.rollback();
            throw e;
        } catch (UserNotExistException e) {
            tran.rollback();
            throw e;
        }
    }

    @Override
    public void modifyPassword(User user, String oldPassword, String newPassword, String newPassword2) throws UserNotLoginException, RequestParameterErrorException, PasswordErrorException {
        try {
            tran.begin();
            userService.modifyPassword(user, oldPassword, newPassword, newPassword2);
            tran.commit();
        } catch (UserNotLoginException e) {
            tran.rollback();
            throw e;
        } catch (RequestParameterErrorException e) {
            tran.rollback();
            throw e;
        } catch (PasswordErrorException e) {
            tran.rollback();
            throw e;
        }
    }
}
